const express = require('express');
const verify = require('../utils/verify.js');
const connect = require('../utils/connect.js');

const userRouter = express.Router();

// 登录
userRouter.post('/login', (req, res) => {
  connect(
    `SELECT * FROM user_list WHERE mobile='${req.body.mobile}'`,
    (err, { code, data, msg }) => {
      if (err) {
        res.send({ code, msg });
      } else {
        if (data?.length < 1) {
          res.send({ code, msg: '请输入正确的手机号！' });
        } else {
          verify.setToKen(req.body.mobile).then((token) => {
            res.send({
              code,
              data: {
                token,
              },
              msg: '登录成功！',
            });
          });
        }
      }
    }
  );
});

// 注册
userRouter.post('/register', (req, res) => {
  connect(
    `INSERT INTO user_list (mobile) VALUES ('${req.body.mobile}')`,
    (err, result) => {
      if (err) {
        res.send(result);
      } else {
        res.send({
          code: 0,
          msg: '注册成功！',
        });
      }
    }
  );
});

module.exports = userRouter;
